<script setup>
import { ref, reactive, toRaw } from 'vue'
import { service, cache } from '@utils'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refresh'])

defineProps({
    types: Array
})

const visible = ref(false)
const formRef = ref()

const state = reactive({
    param: {}
})

const rules = {
    label: [{ required: true, message: '请输入', trigger: 'blur' }],
    val: [{ required: true, message: '请输入', trigger: 'blur' }],
    type: [{ required: true, message: '请选择', trigger: 'change' }]
}

const open = (item) => {
    state.param = { ...item }
    visible.value = true
}

const close = () => {
    visible.value = false
    state.param = {}
}

const sure = async () => {
    formRef.value.validate((valid) => {
        if (valid) {
            realSubmit()
        }
    })
}
const realSubmit = async () => {
    if( !!state.param.id ) {
        const res = await service.sys.argumentEdit(toRaw(state.param))
        if (res) {
            ElMessage.success('修改成功')
        }
    }else{
        const res = await service.sys.argumentSave(toRaw(state.param))
        if (res) {
            ElMessage.success('新增成功')
        }
    }
    close()
    emit('refresh', !!state.param.id)
}
//把方法暴露给父组件
defineExpose({
    open
})
</script>
    
    <template>
    <el-dialog v-model="visible" :title="!!state.param.id ? '修改' : '新增'" center :close-on-click-modal="false" @close="close"
        destroy-on-close :width="500">
        <section>
            <el-form :model="state.param" :rules="rules" ref="formRef" label-width="100px" label-suffix=":" onsubmit="return false;">
                <el-form-item label="参数名" prop="label">
                    <el-input v-model="state.param.label" placeholder="请输入参数名" clearable></el-input>
                </el-form-item>
                <el-form-item label="参数值" prop="val">
                    <el-input v-model="state.param.val" placeholder="请输入参数值" clearable></el-input>
                </el-form-item>
                <el-form-item label="类型" prop="type">
                    <el-select v-model="state.param.type" style="width:100%" placeholder="请选择类型" clearable>
                        <el-option v-for="{label, val} in types" :key="val" :label="label" :value="val" />
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="state.param.remark" placeholder="请输入备注" clearable></el-input>
                </el-form-item>
            </el-form>
        </section>

        <template #footer>
            <span class="flex-align-end">
                <div class="margin-right20">
                    <el-button @click="close">取消</el-button>
                </div>
                <el-button type="primary" @click="sure">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
    